<template>
  <div class="finance-management">
    <!-- 财务汇总看板 - 改为卡片式设计 -->
    <div class="dashboard-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card shadow="hover" class="metric-card income-card">
            <div class="card-content">
              <div class="metric-title">本月应收租金</div>
              <div class="metric-value">{{ summary.currentMonthIncome.toLocaleString() }}<span class="unit">元</span>
              </div>
              <div class="metric-trend">


              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="metric-card arrears-card">
            <div class="card-content">
              <div class="metric-title">当前租金未缴</div>
              <div class="metric-value" :style="{ color: summary.totalArrears > 0 ? '#F56C6C' : '' }">
                {{ summary.totalArrears.toLocaleString() }}<span class="unit">元</span>
              </div>
              <div class="metric-trend">
                <el-icon color="#F56C6C">
                  <Warning />
                </el-icon>
                <span>{{ summary.totalArrears > 0 ? '有未缴账单' : '全部已缴清' }}</span>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="metric-card annual-card">
            <div class="card-content">
              <div class="metric-title">租金年度总收入</div>
              <div class="metric-value">{{ summary.annualIncome.toLocaleString() }}<span class="unit">元</span></div>
              <div class="metric-trend">


              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="metric-card enterprise-card">
            <div class="card-content">
              <div class="metric-title">入驻企业</div>
              <div class="metric-value">{{ summary.enterpriseCount }}<span class="unit">家</span></div>
              <div class="metric-trend">


              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>



    <!-- 账单查询功能区 - 优化后的卡片式设计 -->
    <el-card class="query-card" shadow="never">
      <div class="query-section">
        <el-form :model="queryParams" class="query-form">
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="企业名称" class="query-item">
                <el-input v-model="queryParams.enterpriseName" placeholder="请输入企业名称" clearable suffix-icon="Search"
                  class="query-input" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="账单月份" class="query-item">
                <el-date-picker v-model="queryParams.billMonth" type="month" value-format="YYYY-MM" placeholder="选择月份"
                  clearable class="query-date-picker" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="支付状态" class="query-item">
                <el-select v-model="queryParams.paymentStatus" clearable placeholder="全部状态" class="query-select">
                  <el-option label="未支付" value="unpaid" />
                  <el-option label="已支付" value="paid" />
                  <el-option label="已逾期" value="overdue" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item class="query-item query-buttons">
                <el-button type="primary" @click="handleSearch" icon="Search" class="search-btn">
                  查询
                </el-button>
                <el-button @click="resetSearch" icon="Refresh" class="reset-btn">
                  重置
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </el-card>



    <!-- 账单列表 - 改为卡片式并优化样式 -->
    <el-card class="table-card" shadow="never">
      <el-table :data="billList" style="width: 100%" @selection-change="handleSelectionChange" class="bill-table"
        v-loading="loading">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="billNumber" label="账单编号" width="180" />
        <el-table-column label="企业信息" min-width="200">
          <template #default="{ row }">
            <div class="enterprise-info">
              <div class="name">{{ row.enterpriseName }}</div>
              <div class="meta">
                <el-tag size="small" effect="plain">{{ row.enterpriseType }}</el-tag>
                <span class="enterprise-id">ID: {{ row.enterpriseId }}</span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="billMonth" label="账单月份" width="120" align="center" />
        <el-table-column prop="amount" label="金额" align="right" width="150">
          <template #default="{ row }">
            <span class="amount">{{ row.totalAmount.toLocaleString() }}</span>
            <span class="unit">元</span>
          </template>
        </el-table-column>
        <el-table-column label="支付状态" width="140" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.paymentStatus)" effect="light" class="status-tag">
              <el-icon v-if="row.paymentStatus === 'paid'">
                <CircleCheck />
              </el-icon>
              <el-icon v-else-if="row.paymentStatus === 'overdue'">
                <Warning />
              </el-icon>
              <el-icon v-else>
                <Clock />
              </el-icon>
              {{ getStatusText(row.paymentStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="最晚缴纳时间" width="150" align="center">
          <template #default="{ row }">
            <span>{{ formatDate(row.dueDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button type="success" size="small" @click="markAsPaid(row)" v-if="row.paymentStatus !== 'paid'" plain
                class="action-button">
                <el-icon size="14">
                  <CircleCheck />
                </el-icon>
                标记支付
              </el-button>
              <el-button type="primary" size="small" @click="viewDetails(row)" plain class="action-button">
                <el-icon size="14">
                  <View />
                </el-icon>
                详情
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination 
          v-model:current-page="pagination.current" 
          :page-size="pagination.size" 
          :total="pagination.total"
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[10, 20, 50, 100]" background />
      </div>
    </el-card>

    <!-- 账单详情弹窗 - 保持不变 -->
    <el-dialog v-model="detailVisible" title="账单详情" width="600px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="账单编号">{{
          currentBill.billNumber
          }}</el-descriptions-item>
        <el-descriptions-item label="企业名称">{{
          currentBill.enterpriseName
          }}</el-descriptions-item>
        <el-descriptions-item label="账单月份">{{
          currentBill.billMonth
          }}</el-descriptions-item>
        <el-descriptions-item label="金额">{{ currentBill.totalAmount.toLocaleString() }} 元</el-descriptions-item>
        <el-descriptions-item label="生成时间">{{
          currentBill.createTime
          }}</el-descriptions-item>
        <el-descriptions-item label="到期时间">{{
          formatDate(currentBill.dueDate)
          }}</el-descriptions-item>
        <el-descriptions-item label="支付状态">
          <el-tag :type="getStatusType(currentBill.paymentStatus)">
            {{ getStatusText(currentBill.paymentStatus) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="费用明细" :span="2">
          <el-table :data="currentBill.feeDetails" size="small">
            <el-table-column prop="item" label="项目" />
            <el-table-column prop="amount" label="金额" align="right">
              <template #default="{ row }">
                {{ row.totalAmount.toLocaleString() }} 元
              </template>
            </el-table-column>
          </el-table>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 批量操作确认弹窗 - 保持不变 -->
    <el-dialog v-model="batchDialogVisible" title="批量操作确认" width="400px">
      <div class="batch-dialog-content">
        <p>确认要对选中的 {{ selectedBills.length }} 条账单执行此操作吗？</p>
        <div class="dialog-footer">
          <el-button @click="batchDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmBatchOperation">确认</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 账单管理功能区 - 改为卡片式并增加图标 -->
    <el-card class="action-card" shadow="never">
      <div class="action-section">
        <el-button type="primary" @click="generateBills" class="action-button">
          <el-icon class="button-icon">
            <DocumentAdd />
          </el-icon>
          <span>生成账单</span>
        </el-button>
        <el-button type="success" @click="exportBills" class="action-button">
          <el-icon class="button-icon">
            <Download />
          </el-icon>
          <span>导出账单</span>
        </el-button>
        <el-button type="warning" :disabled="selectedBills.length === 0" @click="sendReminders" class="action-button">
          <el-icon class="button-icon">
            <Bell />
          </el-icon>
          <span>发送催缴通知</span>
        </el-button>
        <div class="selected-count" v-if="selectedBills.length > 0">
          已选择 {{ selectedBills.length }} 条账单
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import {
  DocumentAdd, Download, Bell, Top, Warning, User,
  CircleCheck, Clock, View, Search, Refresh
} from '@element-plus/icons-vue'
import axios from 'axios'

// 创建axios实例
const request = axios.create({
  // 从环境变量获取基础地址，自动适配环境
  baseURL: import.meta.env.VITE_API_BASE_URL,
})
export default {
  components: {
    DocumentAdd,
    Download,
    Bell,
    Top,
    Warning,
    User,
    CircleCheck,
    Clock,
    View,
    Search,
    Refresh
  },
  data() {
    // 生成2025年5月和6月的测试数据
    // const generateTestData = () => {
    //   const enterprises = [
    //     { id: 1, name: 'Tesla广州分公司', type: '技术' },
    //     { id: 2, name: '绿色能源公司', type: '能源' },
    //     { id: 3, name: '广州人工智能实验室', type: '科技' },
    //     { id: 4, name: 'Tesla广州分公司', type: '技术' },
    //     { id: 5, name: '绿色能源公司', type: '能源' },
    //     { id: 6, name: '智慧物流公司', type: '物流' },
    //     { id: 7, name: '生物医药公司', type: '医药' },
    //     { id: 8, name: '广州人工智能实验室', type: '科技' }
    //   ]

    //   const statuses = ['paid', 'unpaid', 'overdue']
    //   const months = ['2025-05', '2025-06']
    //   const bills = []

    //   // 为每家企业生成1-2个账单
    //   enterprises.forEach(enterprise => {
    //     // 随机决定生成1还是2个账单
    //     const billCount = Math.random() > 0.3 ? 2 : 1

    //     for (let i = 0; i < billCount; i++) {
    //       const monthIndex = Math.floor(Math.random() * months.length)
    //       const billMonth = months[monthIndex]
    //       const baseRent = Math.floor(Math.random() * 20000) + 10000
    //       const managementFee = Math.floor(Math.random() * 3000) + 1000
    //       const utilityFee = Math.floor(Math.random() * 2000) + 500
    //       const totalAmount = baseRent + managementFee + utilityFee

    //       const statusIndex = Math.floor(Math.random() * statuses.length)
    //       const paymentStatus = statuses[statusIndex]

    //       const dueDate = billMonth === '2025-05' ? '2025-06-15' : '2025-07-15'
    //       const createTime = billMonth === '2025-05' ? '2025-05-01' : '2025-06-01'

    //       bills.push({
    //         billNumber: `账单-${enterprise.id}-${billMonth}-${i + 1}`,
    //         enterpriseId: enterprise.id,
    //         enterpriseName: enterprise.name,
    //         enterpriseType: enterprise.type,
    //         billMonth: billMonth,
    //         amount: totalAmount,
    //         paymentStatus: paymentStatus,
    //         dueDate: dueDate,
    //         createTime: `${createTime} ${Math.floor(Math.random() * 12) + 8}:00:00`,
    //         feeDetails: [
    //           { item: '基础租金', amount: baseRent },
    //           { item: '物业管理费', amount: managementFee },
    //           { item: '水电费', amount: utilityFee }
    //         ]
    //       })
    //     }
    //   })

    //   return bills
    // }

    return {
      loading: false,
      queryParams: {
        enterpriseName: '',
        billMonth: '',
        paymentStatus: '',
        current: 1,   
      size: 10
      },
      summary: {
        currentMonthIncome: 0,
        totalArrears: 0,
        annualIncome: 0,
        enterpriseCount: 0
      },
      billList: [],
      // originalBillList: [],
      detailVisible: false,
      batchDialogVisible: false,
      currentBill: {},
      selectedBills: [],
      pagination: {
        current: 1,
        size: 10,
        total: 0
      },
      currentOperation: ''
    }
  },
  created() {
    // this.originalBillList = JSON.parse(JSON.stringify(this.billList))
    this.pagination.total = this.billList.length
    // 重新计算汇总数据
    // this.calculateSummary()
    // 新增：从后端加载数据
  this.loadSummaryData()    // 新增方法
  this.loadBillList()       // 新增方法
  },
  methods: {
    formatDate(dateString) {
      if (!dateString) return ''
      // 如果日期字符串包含时间，只取日期部分
      return dateString.split('T')[0]
    },
    handleSearch() {
      // this.loading = true
      // setTimeout(() => {
      //   // this.billList = this.originalBillList.filter(bill => {
      //   //   const nameMatch = this.queryParams.enterpriseName
      //   //     ? bill.enterpriseName.toLowerCase().includes(
      //   //       this.queryParams.enterpriseName.toLowerCase()
      //   //     )
      //   //     : true

      //   //   const monthMatch = this.queryParams.billMonth
      //   //     ? bill.billMonth === this.queryParams.billMonth
      //   //     : true

      //   //   const statusMatch = this.queryParams.paymentStatus
      //   //     ? bill.paymentStatus === this.queryParams.paymentStatus
      //   //     : true

      //   //   return nameMatch && monthMatch && statusMatch
      //   // })
      //   this.pagination.total = this.billList.length
      //   this.loading = false
      //   this.$message.success(`找到 ${this.billList.length} 条账单记录`)
      // }, 500)
      this.pagination.current = 1
      this.loadBillList() // 改为调用API
    },
    
    resetSearch() {
      this.queryParams = {
        enterpriseName: '',
        billMonth: '',
        paymentStatus: '',
        current: 1,    // 需要添加
        size: 10       // 需要添加
      }

      this.loadBillList() // 改为调用API
    },

    getStatusType(status) {
      const types = {
        paid: 'success',
        unpaid: 'danger',
        overdue: 'warning'
      }
      return types[status] || ''
    },

    getStatusText(status) {
      const texts = {
        paid: '已支付',
        unpaid: '未支付',
        overdue: '已逾期'
      }
      return texts[status] || status
    },

    viewDetails(row) {
      this.currentBill = row
      this.detailVisible = true
    },

    async markAsPaid(row) {

      try {
        await this.$confirm('确认将该账单标记为已支付?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        await request.post(`/api/bills/markAsPaid/${row.id}`)
        this.$message.success('账单状态已更新')
        // 重新从后端加载数据
        this.loadBillList()
        this.loadSummaryData()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('操作失败')
        }
      }
    },
    handleSelectionChange(selection) {
      this.selectedBills = selection
    },
    async generateBills() {

      try {
        await this.$confirm('确认生成本月所有企业的账单?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const currentMonth = new Date().toISOString().slice(0, 7)
        await request.post('/api/bills/generate', null, {
          params: { month: currentMonth }
        })
        this.$message.success('账单生成成功')
        this.loadBillList()
        this.loadSummaryData()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('生成账单失败')
        }
      }
    },
    async exportBills() {

      try {
        await this.$confirm('确认导出当前筛选条件下的账单?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await request.post('/api/bills/export', this.queryParams, {
          responseType: 'blob'
        })
        
        // 文件下载处理逻辑
        const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = `账单导出_${new Date().toISOString().slice(0, 10)}.xlsx`
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
        
        this.$message.success('账单导出成功')
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('导出账单失败')
        }
      }
    },

    async sendReminders() {
  if (this.selectedBills.length === 0) {
    this.$message.warning('请选择要催缴的账单')
    return
  }
  
      try {
        const billIds = this.selectedBills.map(bill => bill.id)
        await request.post('/api/bills/sendReminders', billIds)
        this.$message.success(`已成功发送 ${this.selectedBills.length} 条催缴通知`)
        this.selectedBills = []
      } catch (error) {
        this.$message.error('发送催缴通知失败')
      }
    },
    async confirmBatchOperation() {
      if (this.currentOperation === 'remind') {
        // 调用发送催缴通知的API
      try {
      const billIds = this.selectedBills.map(bill => bill.id)
      await request.post('/api/bills/sendReminders', billIds)
      this.$message.success(`已成功发送 ${this.selectedBills.length} 条催缴通知`)

    } catch (error) {
      this.$message.error('发送催缴通知失败')
    }
      }
      this.batchDialogVisible = false
      this.selectedBills = []
    },
    handlePageChange(current) {
      this.pagination.current = current
      this.loadBillList() // 改为调用API
    },
    handleSizeChange(size) {
      this.pagination.size = size;
      this.pagination.current = 1; // 重置到第一页
      this.loadBillList();
    },
    // 新增：加载汇总数据
    async loadSummaryData() {
      try {
        const res = await request.get('/api/bills/dashboard/summary')
        
        this.summary = {
          currentMonthIncome: res.data.data?.currentMonthIncome || 0,
          totalArrears: res.data.data?.totalArrears || 0,
          annualIncome: res.data.data?.annualIncome || 0,
          enterpriseCount: res.data.data?.enterpriseCount || 0
        }
      } catch (e) {
        this.summary = { currentMonthIncome: 0, totalArrears: 0, annualIncome: 0, enterpriseCount: 0 }
      }
    },

    // 新增：加载账单列表
    async loadBillList() {
      this.loading = true
      try {
        const res = await request.post('/api/bills/query', {
          ...this.queryParams,
          current: this.pagination.current,
          size: this.pagination.size
        })


        const pageData = res.data.data || {}
        this.billList = Array.isArray(pageData.records) ? pageData.records : []
        this.pagination.total = pageData.total || 0
      } catch (e) {
        this.billList = []       // 异常也兜底
        this.pagination.total = 0
        this.$message.error('加载账单列表失败')
      } finally {
        this.loading = false
      }
    }
    
  }
}
</script>

<style scoped lang="scss">
.finance-management {
  padding: 20px;
  background-color: #f5f7fa;
}

.dashboard-cards {
  margin-bottom: 20px;

  .metric-card {
    border-radius: 8px;
    border: none;
    transition: transform 0.3s;
    height: 120px;

    &:hover {
      transform: translateY(-5px);
    }

    .card-content {
      padding: 15px;

      .metric-title {
        font-size: 14px;
        color: #606266;
        margin-bottom: 10px;
      }

      .metric-value {
        font-size: 24px;
        font-weight: bold;
        margin-bottom: 5px;

        .unit {
          font-size: 14px;
          margin-left: 4px;
          color: #909399;
        }
      }

      .metric-trend {
        display: flex;
        align-items: center;
        font-size: 12px;
        color: #909399;

        .el-icon {
          margin-right: 5px;
        }
      }
    }

    &.income-card {
      border-left: 4px solid #67C23A;
    }

    &.arrears-card {
      border-left: 4px solid #F56C6C;
    }

    &.annual-card {
      border-left: 4px solid #E6A23C;
    }

    &.enterprise-card {
      border-left: 4px solid #409EFF;
    }
  }
}
.action-buttons {
  display: flex;
  gap: 8px; /* 按钮之间的间距 */
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
}
/* 确保按钮内的图标和文字对齐 */
.action-button .el-icon {
  margin-right: 4px;
}
.action-card {
  margin-bottom: 20px;
  border-radius: 8px;

  .action-section {
    display: flex;
    align-items: center;
    gap: 15px;

    .action-button {
      display: flex;
      align-items: center;
      flex: 1;
      /* 让按钮平均分配宽度 */
      min-width: 0;
      /* 防止文本溢出 */
      display: inline-flex;
      align-items: center;
      justify-content: center;

      .button-icon {
        margin-right: 5px;
      }
    }

    .selected-count {
      margin-left: auto;
      color: #606266;
      font-size: 14px;
    }
  }
}


.query-card {
  margin-bottom: 20px;
  border-radius: 8px;
  background-color: #fff;

  :deep(.el-card__body) {
    padding: 20px;
  }
}

.query-form {
  .el-row {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
  }

  .query-item {
    margin-bottom: 0;
    width: 100%;

    :deep(.el-form-item__label) {
      font-size: 14px;
      color: #606266;
      padding-right: 10px;
      line-height: 36px;
    }

    :deep(.el-form-item__content) {
      display: flex;
      align-items: center;
    }
  }

  .query-input,
  .query-select,
  .query-date-picker {
    width: 100%;

    :deep(.el-input__inner) {
      height: 36px;
      line-height: 36px;
    }

    :deep(.el-input__icon) {
      line-height: 36px;
    }
  }

  .query-buttons {
    display: flex;
    justify-content: flex-end;
    gap: 10px;

    .search-btn,
    .reset-btn {
      padding: 8px 15px;
      height: 36px;
      display: inline-flex;
      /* 新增 */
      align-items: center;
      /* 新增 - 垂直居中 */
      justify-content: center;
      /* 新增 - 水平居中 */
    }

    .search-btn {
      background-color: #409EFF;
      border-color: #409EFF;
    }

    .reset-btn {
      color: #606266;
      border-color: #dcdfe6;

      &:hover {
        color: #409EFF;
        border-color: #c6e2ff;
        background-color: #ecf5ff;
      }
    }
  }
}

@media (max-width: 768px) {
  .query-form {
    .el-col {
      margin-bottom: 15px;
    }

    .query-buttons {
      justify-content: flex-start;
    }
  }
}


.table-card {
  border-radius: 8px;

  .bill-table {
    .enterprise-info {
      .name {
        font-weight: 500;
        margin-bottom: 5px;
      }

      .meta {
        display: flex;
        align-items: center;
        gap: 8px;

        .enterprise-id {
          font-size: 12px;
          color: #909399;
        }
      }
    }

    .amount {
      font-weight: 500;
    }

    .unit {
      font-size: 12px;
      color: #909399;
      margin-left: 2px;
    }

    .status-tag {
      display: flex;
      align-items: center;
      gap: 5px;
    }
  }

  .pagination-wrapper {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}

.batch-dialog-content {
  text-align: center;

  p {
    margin-bottom: 20px;
    font-size: 16px;
  }

  .dialog-footer {
    display: flex;
    justify-content: center;
    gap: 20px;
  }
}
</style>